package com.mybatis.number.servlet;

import com.mybatis.number.dao.MyBatisConnectionFactory;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.mybatis.number.model.Number;
import java.util.ArrayList;

@WebServlet(name = "Insert", urlPatterns = {"/insert"})
public class Insert extends HttpServlet {

  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();

      SqlSession session = sqlSessionFactory.openSession();

      Number number = new Number();
      number.setId(new Byte(request.getParameter("number")));
      number.setDescription(request.getParameter("description"));

      session.insert("NumberMapper.insert", number);

      session.commit();

/*------------------------*/
      ArrayList<Number> numbers =(ArrayList<Number>) session.selectList("NumberMapper.selectByExample");

      for (Number number1 : numbers) {
        out.print(number1.toString()+"<br/>");
      }

    } catch (Exception ex) {
      out.print(ex);
    } finally {
      out.close();
    }
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    processRequest(request, response);
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    processRequest(request, response);
  }
}
